﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.IO;

using WCFMINERP.COM;
using WCFMINERP.Contracts.InterFaces;
using WCFMINERP.Contracts.DataContracts;
using WCFMINERP.ContextPropagation;
using WCFMINERP.ComControls;
using System.Xml;
using WCFMINERP.SharpZipLib;
using FastReport;


namespace WCFMINERP.Client
{
    public partial class FrmUpload : FrmParent
    {
        public FrmUpload()
        {
            InitializeComponent();
        }

        ChannelFactory<ITransferFile> _proxyTransfer;//创建代理
        ITransferFile transfer;
        List<TransferFileInfo> tranferList = new List<TransferFileInfo>();//上传列表
        TransferFileInfo packingFileInfo = new TransferFileInfo();
        bool _isUploadRuning = false;//控制上传
        bool _isPackageRuning = false;//控制打包
        int MaxSize = 1024 * 100;  //设置每次传100k  
        int timeSpan = 0;//上传的时间间隔
        string WorkFolder = Environment.CurrentDirectory + "\\OrderFileTemp";


        ChannelFactory<IQuery> _proxyQuery;//创建查询代理
        IQuery query;


        private void FrmUpload_Load(object sender, EventArgs e)
        {
            toolStripButtonStart.Enabled = false;
            toolStripButtonStop.Enabled = false;
            toolStripButtonDelete.Enabled = false;
            //timeSpan = 1000/((double)Properties.Settings.Default.Speed / MaxSize) ;
            timeSpan = Convert.ToInt32((double)1000 * MaxSize / Properties.Settings.Default.Speed);
            backgroundWorkerupload.WorkerReportsProgress = true;
            backgroundWorkerupload.WorkerSupportsCancellation = true;
            backgroundWorkerCopyAndPackage.WorkerReportsProgress = true;
            backgroundWorkerCopyAndPackage.WorkerSupportsCancellation = true;
            backgroundWorkerselectProduct.WorkerReportsProgress = true;
            backgroundWorkerselectProduct.WorkerSupportsCancellation = true;
            backgroundWorkerSelectBill.WorkerReportsProgress = true;
            backgroundWorkerSelectBill.WorkerSupportsCancellation = true;
            try
            {
                _proxyQuery = new ChannelFactory<IQuery>("Query");
                query = _proxyQuery.CreateChannel();
                _proxyTransfer = new ChannelFactory<ITransferFile>("TransferFile");
                transfer = _proxyTransfer.CreateChannel();
                InitAlpha();
                tranferList = transfer.GetShopFileList();
                gridControlUploading.DataSource = tranferList;
                gridControlUploading.RefreshDataSource();
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接到冲印车间失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
        #region//上传线程
        private void backgroundWorkerupload_DoWork(object sender, DoWorkEventArgs e)
       {
            
            _isUploadRuning = true;
            List<TransferFileInfo> listUploading = tranferList.Where(p => p.Status == (int)TransferStatus.Doing).ToList();
            if (listUploading.Count < 1)//检查是否还有文件要上传
            {
                try
                {
                    InitAlpha();
                    tranferList = transfer.GetShopFileList();
                    listUploading = tranferList.Where(p => p.Status == (int)TransferStatus.Doing).ToList();

                }
                catch (Exception exxx)
                {
                    backgroundWorkerupload.ReportProgress(100,"");
                    _isUploadRuning = false;
                    return;
                }
            }
            if (listUploading.Count == 0)
            {
                _isUploadRuning = false;
                return;
            }

            try
            {
                TransferFileInfo file = listUploading.OrderBy(p => p.CreateTime).FirstOrDefault();
                TransferFileInfo saveFile = new TransferFileInfo();
                FileStream stream = System.IO.File.OpenRead(file.ShopTempPath);    //读取本地文件                  
                if (file.Length == file.Offset) //如果文件的长度等于文件的偏移量，说明文件已经上传完成
                {
                    //MessageBox.Show("该文件已经在服务器中,不用上传！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                   //发送文件传输完成命令告诉服务器
                    transfer.EndTransfer(file.Name);
                    File.Delete(file.ShopTempPath);///删除本地文件
                    _isUploadRuning = false;///刷新重新尝试
                    return;
                }
                else
                {
                    while (file.Length != file.Offset && file.Status == (int)TransferStatus.Doing)
                    {
                        try
                        {
                            file.Data = new byte[file.Length - file.Offset <= MaxSize ? file.Length - file.Offset : MaxSize]; //设置传递的数据的大小
                            stream.Position = file.Offset; //设置本地文件数据的读取位置
                            stream.Read(file.Data, 0, file.Data.Length);//把数据写入到file.Data中
                            //要捕捉连接不上的异常
                            InitAlpha();
                            saveFile = transfer.UplodaFile(file);     //上传显示
                            file.Offset = saveFile.Offset;
                            file.SaveTime = saveFile.SaveTime;

                            backgroundWorkerupload.ReportProgress(0, saveFile);
                        }
                        catch (Exception Ue)
                        {
                            backgroundWorkerupload.ReportProgress(100, "");
                        }

                        //System.Threading.Thread.Sleep(timeSpan);//控制速度
                    }
                    stream.Close();
                    if (file.Length == file.Offset)
                    {
                        File.Delete(file.ShopTempPath);///删除本地文件
                        backgroundWorkerupload.ReportProgress(1, saveFile);
                    }
                    else
                    {
                        ///暂停单子
                        transfer.StopUploadQueue(file);
                    }
                }
                //}

                //}
            }
            catch (Exception exxx)
            {

                _isUploadRuning = false;
            }

            _isUploadRuning = false;
        }

        private void backgroundWorkerupload_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage != 100)
            {
                if (!this.Text.Equals("上传与查询"))
                {
                    this.Text = "上传与查询";
                }
                TransferFileInfo info = (TransferFileInfo)e.UserState;
                TransferFileInfo inEXit = tranferList.FirstOrDefault(p => p.Name == info.Name);
                if (inEXit != null)
                {


                    inEXit.LastGuage = info.LastGuage;
                    inEXit.LastTime = info.LastTime;
                    inEXit.Offset = info.Offset;
                    inEXit.SaveTime = info.SaveTime;


                }
                else
                {
                    tranferList.Add(inEXit);
                }

                if (e.ProgressPercentage == 1)
                {
                    _isUploadRuning = false;///
                    transfer.EndTransfer(info.Name);
                    //inEXit.Offset = inEXit.Length;
                    //inEXit.LastGuage = inEXit.Offset;
                    //调用赋值函数
                    WCFMINERP.ContextPropagation.ApplicationContext.Current.Shopid = Shop.ShopId;
                    tranferList = transfer.GetShopFileList();

                }
                gridControlUploading.DataSource = tranferList;
                gridControlUploading.RefreshDataSource();
            }
            else
            {
                if (!this.Text.Equals("上传与查询-离线"))
                {
                    this.Text = "上传与查询-离线";
                }
            }

        }

        private void backgroundWorkerupload_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }


        private void timerUpload_Tick(object sender, EventArgs e)
        {
            if (!_isUploadRuning)
            {
                try
                {

                    backgroundWorkerupload.RunWorkerAsync();
                }
                catch
                {
                    _isUploadRuning = false;
                }
            }

        }
        #endregion
        private void FrmUpload_FormClosing(object sender, FormClosingEventArgs e)
        {

            //_proxyTransfer.Close();
            if (e.CloseReason == CloseReason.UserClosing)
            {

                e.Cancel = true;
                this.Hide();
            }
        }
        //界面列表刷新
        private void timerRush_Tick(object sender, EventArgs e)
        {
            //    if (packingFileInfo != null)
            //    {
            //        if (tranferList.FirstOrDefault(p => p.Name == packingFileInfo.Name) == null)
            //        {
            //            tranferList.Add(packingFileInfo);
            //        }

            //    }
            //    tranferList.Remove(tranferList.FirstOrDefault(p=>String.IsNullOrEmpty(p.Name)));
            tranferList = transfer.GetShopFileList();
            gridControlUploading.DataSource = tranferList;

            gridControlUploading.RefreshDataSource();


        }
        #region//订单包操作
        private void gridViewUploading_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                if (e.Column.Name == "gridColumn7")
                {
                    int status = (int)e.CellValue;
                    switch (status)
                    {
                        case (int)TransferStatus.Wait:
                            e.DisplayText = "准备上传";
                            break;
                        case (int)TransferStatus.Doing:
                            e.DisplayText = "正在上传";
                            break;
                        case (int)TransferStatus.Done:
                            e.DisplayText = "完成";
                            break;
                        case (int)TransferStatus.Stop:
                            e.DisplayText = "暂停";
                            break;
                        case (int)TransferStatus.Error:
                            e.DisplayText = "错误";
                            break;
                        default:
                            e.DisplayText = "完成";
                            break;
                    }
                }
            }
        }

        private void toolStripButtonStart_Click(object sender, EventArgs e)
        {
            if (currOperTranFile != null && MessageBox.Show("确定要继续上传订单包" + currOperTranFile.Name + "的上传吗？", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                //currOperTranFile.Status = (int)TransferStatus.Doing;
                TransferFileInfo tran = tranferList.FirstOrDefault(tf => tf.Name == currOperTranFile.Name);
                if (tran == null)
                {
                    MessageBox.Show("订单包未取得");
                    return;
                }
                tran.Status = (int)TransferStatus.Doing;
                var aaa = transfer.InitTransferFile(tran);
            }
        }

        private void toolStripButtonStop_Click(object sender, EventArgs e)
        {
            if (currOperTranFile != null && MessageBox.Show("确定要暂停订单包" + currOperTranFile.Name + "的上传吗？", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                //currOperTranFile.Status = (int)TransferStatus.Stop;
               TransferFileInfo a= tranferList.FirstOrDefault(tf => tf.Name == currOperTranFile.Name);
               a.Status = (int)TransferStatus.Stop;
               transfer.StopUploadQueue(a);
               gridControlUploading.DataSource = tranferList;

               gridControlUploading.RefreshDataSource();
            }
        }
        TransferFileInfo currOperTranFile = new TransferFileInfo();
        private void gridViewUploading_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                currOperTranFile = (TransferFileInfo)gridViewUploading.GetRow(e.RowHandle);
                if (currOperTranFile.Status == (int)TransferStatus.Stop)
                {
                    toolStripButtonStart.Enabled = true;
                    toolStripButtonStop.Enabled = false;
                    toolStripButtonDelete.Enabled = true;
                }
                else if (currOperTranFile.Status == (int)TransferStatus.Doing)
                {
                    toolStripButtonStop.Enabled = true;
                    toolStripButtonStart.Enabled = false;
                    toolStripButtonDelete.Enabled = false;
                }

            }
        }
        #endregion
        /// <summary>
        /// 初始化本次操作的参数
        /// </summary>
        void InitAlpha()
        {
            WCFMINERP.ContextPropagation.ApplicationContext.Current.Shopid = Shop.ShopId;
            WCFMINERP.ContextPropagation.ApplicationContext.Current.ShopName = Shop.shopName;
            //WCFMINERP.ContextPropagation.ApplicationContext.Current.MachineName=Shop.m
            //WCFMINERP.ContextPropagation.ApplicationContext.Current.SHACODE=Shop.s
        }

        private void backgroundWorkerCopyAndPackage_DoWork(object sender, DoWorkEventArgs e)
        {

            DirectoryInfo root = new DirectoryInfo(WorkFolder);
            DirectoryInfo[] OrderForderArry = root.GetDirectories();
            foreach (DirectoryInfo orderForder in OrderForderArry.OrderBy(di => di.CreationTime))//按时间顺序依次拷贝文件及打包
            {
                //if (orderForder.GetDirectories().Count() > 0)
                //{
                //    continue;
                //}
                FileInfo[] fileArray = orderForder.GetFiles("*.zip");//获取已经压缩好的文件进行上传尝试
                foreach (FileInfo file in fileArray)
                {
                    InitAlpha();
                    TransferFileInfo rtnFileInfo = transfer.InitTransferFile(packingFileInfo);
                    if (rtnFileInfo != null)
                    {
                        backgroundWorkerCopyAndPackage.ReportProgress(0, rtnFileInfo);
                    }


                }
                packingFileInfo = new TransferFileInfo();
                XmlDocument xml = new XmlDocument();
                string orderFolderPath = orderForder.FullName;
                try
                {
                    xml.Load(orderFolderPath + "\\" + orderForder.Name + ".xml");
                }
                catch
                {
                    //报错处理
                }
                packingFileInfo.Name = orderForder.Name;
                packingFileInfo.ShopName = base.Shop.shopName;
                //packingFileInfo.
                packingFileInfo.ShopID = base.Shop.ShopId;
                packingFileInfo.CreateTime = DateTime.Now;
                packingFileInfo.MachineName = base.Shop.MachineName;
                packingFileInfo.Length = 0;
                packingFileInfo.Status = (int)TransferStatus.CopyPhoto;

                XmlNode xnOrderBag = xml.SelectSingleNode(@"orderbag");
                XmlNodeList xmOrderList = xnOrderBag.ChildNodes;
                foreach (XmlNode xnorder in xmOrderList)
                {
                    XmlAttributeCollection orderInfoXacArray = xnorder.Attributes;
                    string orderProductPath = orderFolderPath + "\\" + orderInfoXacArray["OrderPath"].Value;
                    XmlNodeList xmPhotoList = xnorder.ChildNodes;
                    foreach (XmlNode xnPhoto in xmPhotoList)
                    {
                        XmlAttributeCollection orderPhotoXacArray = xnPhoto.Attributes;
                        string photoPath = orderProductPath + "\\" + orderPhotoXacArray["picPath"].Value;
                        string photoSrcPath = orderPhotoXacArray["OrilPicPath"].Value;
                        string photoDir = photoPath.Substring(0, photoPath.LastIndexOf("\\"));
                        if (!Directory.Exists(photoDir))
                        {
                            Directory.CreateDirectory(photoDir);
                        }
                        int isSucc = FileOperate.CopyFileA(photoSrcPath, photoPath, 0);
                        if (isSucc < 1)
                        {
                            //拷贝文件失败标志订单错误 重新开单
                            packingFileInfo.Status = (int)TransferStatus.Error;
                            packingFileInfo.Remark = "开单文件被移动，请确认";
                            backgroundWorkerCopyAndPackage.ReportProgress(0, packingFileInfo);
                            //_isPackageRuning = false;//标志不忙
                            continue;
                        }
                    }
                    //文件拷贝完成后重命名，防止再次开单
                    string srcDir = orderInfoXacArray["OrilOrderPath"].Value;
                    FileOperate.MoveFile(srcDir, srcDir + "OK", 2);

                }//拷贝文件完成

                ///打包
                packingFileInfo.Status = (int)TransferStatus.Package;
                string zipFile = WorkFolder + "\\" + orderForder.Name + ".zip";
                try
                {
                    ZipClass.ZipFolder(zipFile, orderForder.FullName);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                if (File.Exists(zipFile))///检查下是否打包成功
                {
                    ///打包成功删掉原来的文件夹
                    Directory.Delete(orderForder.FullName, true);
                }
                else
                {
                    ///重试
                }
                FileInfo fileInfo = new FileInfo(zipFile);
                packingFileInfo.Length = fileInfo.Length;
                packingFileInfo.Status = (int)TransferStatus.Wait;
                packingFileInfo.ShopTempPath = zipFile;
                InitAlpha();
                try
                {
                    TransferFileInfo rtnFileInfo = transfer.InitTransferFile(packingFileInfo);
                    if (rtnFileInfo != null)
                    {
                        backgroundWorkerCopyAndPackage.ReportProgress(0, rtnFileInfo);
                    }
                    //if (rtnVal == 0)
                    //{
                    //    //正常准备上传
                    //}
                    //else if (rtnVal == -1)
                    //{
                    //    packingFileInfo.Remark = "客户端错误";
                    //    packingFileInfo.Status = (int)TransferStatus.Error;
                    //}
                    //else
                    //{
                    //    packingFileInfo.Remark = "此单已经上传过不能重复上传";
                    //    packingFileInfo.Status = (int)TransferStatus.Error;
                    //}
                }
                catch (Exception ex)
                {
                    packingFileInfo.Remark = "连接服务器失败";
                    packingFileInfo.Status = (int)TransferStatus.Error;
                }

            }
            _isPackageRuning = false;



        }

        private void timerCopyFileAndPackage_Tick(object sender, EventArgs e)
        {
            if (!_isPackageRuning)
            {
                _isPackageRuning = true;
                try
                {
                    backgroundWorkerCopyAndPackage.RunWorkerAsync();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    _isPackageRuning = false;
                }
            }


        }

        private void backgroundWorkerCopyAndPackage_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            TransferFileInfo info = (TransferFileInfo)e.UserState;
            if (!string.IsNullOrEmpty(info.Name))
            {
                TransferFileInfo extist = tranferList.FirstOrDefault(p => p.Name == info.Name);
                if (extist == null)
                {
                    tranferList.Add(info);
                }
                else
                {
                    extist.Status = info.Status;
                    extist.Remark = info.Remark;
                }
            }
        }

        private void backgroundWorkerCopyAndPackage_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            _isPackageRuning = false;
        }

        private void toolStripButtonCreateNewOrder_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButtonReplay_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButtonSetting_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        {
            if (currOperTranFile != null && MessageBox.Show("确定要删除上传订单包" + currOperTranFile.Name + "？", "确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {

                if (currOperTranFile.Status == (int)(TransferStatus.Stop))
                {
                    int intVal = transfer.DeleteUploadQueue(currOperTranFile);
                    if (intVal == 1)
                    {
                        currOperTranFile.Status = (int)TransferStatus.Delete;
                        transfer.InitTransferFile(currOperTranFile);
                        MessageBox.Show("删除成功");
                    }
                    else
                    {
                        MessageBox.Show("删除失败，可能服务未启动，请稍候再试");
                    }
                }
            }
        }

        private void buttonok_Click(object sender, EventArgs e)
        {

            double day = (dateTimePickerEnd.Value - dateTimePickerStartTime.Value).TotalDays;

            if (day < 0)
            {
                MessageBox.Show("结束时间应该晚于开始时间");
                return;
            }
            if (day > 30)
            {
                MessageBox.Show("查询不能超过30天");
                return;
            }
            backgroundWorkerselectProduct.RunWorkerAsync();
            if (checkBoxDisplayPrice.Checked)
            {
                gridColumn13.Visible = true;
            }
            else
            {
                gridColumn13.Visible = false;
            }

        }

        private void buttonBillOk_Click(object sender, EventArgs e)
        {
            FrmPwd frmpwd=new FrmPwd();
            if (string.IsNullOrEmpty(Properties.Settings.Default.PricePWD))
            {
                double day = (dateTimePickerBillEnd.Value - dateTimePickerBillStart.Value).TotalDays;

                if (day < 0)
                {
                    MessageBox.Show("结束时间应该晚于开始时间");
                    return;
                }
                if (day > 30)
                {
                    MessageBox.Show("查询不能超过31天");
                    return;
                }
                backgroundWorkerSelectBill.RunWorkerAsync();
            }
            else
            {
                if (DialogResult.OK == frmpwd.ShowDialog())
                {
                    double day = (dateTimePickerBillEnd.Value - dateTimePickerBillStart.Value).TotalDays;

                    if (day < 0)
                    {
                        MessageBox.Show("结束时间应该晚于开始时间");
                        return;
                    }
                    if (day > 30)
                    {
                        MessageBox.Show("查询不能超过31天");
                        return;
                    }
                    backgroundWorkerSelectBill.RunWorkerAsync();
                }
                else
                {
                    MessageBox.Show("请输入正确密码");
                }
            }
        }

        private void tabControlUpLoad_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControlUpLoad.SelectedIndex == 1)
            {
                toolStripStatusLabelBlance.Text = query.GetShopBlance(Shop.ShopId).ToString("0.000")+"元";
                dateTimePickerStartTime.Value = DateTime.Today.AddDays(-7);
                dateTimePickerEnd.Value = DateTime.Today;
            }
            else if (tabControlUpLoad.SelectedIndex == 2)
            {
                
            }
        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        private void gridViewProduct_MasterRowGetRelationName(object sender, DevExpress.XtraGrid.Views.Grid.MasterRowGetRelationNameEventArgs e)
        {
            e.RelationName = "照片";
        }

        private void gridViewProduct_MasterRowGetChildList(object sender, DevExpress.XtraGrid.Views.Grid.MasterRowGetChildListEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                OrderInfoQuary selectRow = (OrderInfoQuary)gridViewProduct.GetRow(e.RowHandle);
                e.ChildList = selectRow.PhotoList;
            }
        }

        private void gridViewBillMain_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                SHOP_Bill_Info spi = (SHOP_Bill_Info)gridViewBillMain.GetRow(e.RowHandle);

               
                DataTable productTable = CreateShopBillDetail();
                DataTable detailTable = CreateShopBillSubDetail();
                foreach (var bdi in spi.List_Detail)
                {
                    DataRow row = productTable.NewRow();
                    row["BillDetailId"] = bdi.BillDetailId;
                    row["OrderInfoCode"] = bdi.OrderInfoCode;
                    row["OrderProductName"] = bdi.OrderProductName;
                    row["CtmName"] = bdi.CtmName;
                    row["Remark"] = bdi.Remark;
                    row["OrderBagName"] = bdi.OrderBagName;
                    productTable.Rows.Add(row);

                    foreach (var bddi in bdi.ListDetail_Detail)
                    {
                        DataRow rowSub = detailTable.NewRow();
                        rowSub["DetailName"] = bddi.DetailName;
                        rowSub["BillDetailId"] =bdi.BillDetailId;
                     
                        rowSub["Spec"] = bddi.Spec;
                        rowSub["Num"] = bddi.Num;
                        rowSub["UnitPrice"] = bddi.UnitPrice;


                        rowSub["Area"] = bddi.Area;
                        rowSub["Type"] = bddi.Type;
                        rowSub["Count"] = bddi.Count;
                        detailTable.Rows.Add(rowSub);
 
                    }
                }
                productTable.TableName = "Prodrct";
                detailTable.TableName = "Detail";
                DataSet set = new DataSet("ds");
                set.Tables.Add(productTable);
                set.Tables.Add(detailTable);
                Report report = new Report();
                 report.Preview = previewControl1;
                 report.Load(Application.StartupPath + "\\Bill.frx");
                set.WriteXml(Application.StartupPath+"\\Bill.xml", XmlWriteMode.WriteSchema);
                report.SetParameterValue("ParaPringtDate",spi.CreateTime.ToString());
                report.SetParameterValue("ParaOrderNum", spi.BillOrderCode.ToString());
                report.SetParameterValue("ParaBillID", spi.BillId.ToString());
                report.RegisterData(productTable, "Prodrct");
                report.RegisterData(detailTable, "Detail");
                previewControl1.Refresh();
                report.Show();
            }
        }
        /// <summary>
        /// 创建明细产品
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("OrderInfoCode", typeof(string));
            table.Columns.Add("OrderProductName", typeof(string));
            table.Columns.Add("CtmName", typeof(string));
            table.Columns.Add("Remark", typeof(string));
            table.Columns.Add("OrderBagName", typeof(string));
            return table;
        }
        /// <summary>
        /// 创建明细收费项目表
        /// 
        /// </summary>
        /// <returns></returns>
        private DataTable CreateShopBillSubDetail()
        {
            DataTable table = new DataTable();
            table.Columns.Add("BillDetailId", typeof(int));
            table.Columns.Add("DetailName", typeof(string));
            table.Columns.Add("Spec", typeof(string));
            table.Columns.Add("Num", typeof(int));
            table.Columns.Add("UnitPrice", typeof(double));
            table.Columns.Add("Count", typeof(double));
            table.Columns.Add("Area", typeof(double));
            table.Columns.Add("Type", typeof(int));
            return table;
        }

        private void backgroundWorkerselectProduct_DoWork(object sender, DoWorkEventArgs e)
        {
            backgroundWorkerselectProduct.ReportProgress(0, "");

            string ctmName = textBoxCtmName.Text.Trim();
            string ProductName = textBoxProductName.Text.Trim();
            string startTime = dateTimePickerStartTime.Value.ToString("yyyy-MM-dd");
            string endTime = dateTimePickerEnd.Value.ToString("yyyy-MM-dd");
            string[] paraArray = new string[4] { ctmName, ProductName, startTime, endTime };

            try
            {
                //MessageBox.Show(Shop.shopName+Shop.ShopId);
               
                List<OrderInfoQuary> listOrder = query.OrderQuery(paraArray,Shop.ShopId);
                //MessageBox.Show(Shop.address);
                backgroundWorkerselectProduct.ReportProgress(1, listOrder);
            }
            catch (Exception ex)
            {
                MessageBox.Show("连接冲印车间失败" + ex.Message);

            }
            finally
            {
                backgroundWorkerselectProduct.ReportProgress(100, "");
            }
        }

        private void backgroundWorkerselectProduct_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 0)
            {
                this.Cursor = Cursors.WaitCursor;
                buttonok.Enabled = false;
            }
            else if (e.ProgressPercentage == 1)
            {

                List<OrderInfoQuary> listOrder = (List<OrderInfoQuary>)e.UserState;
                if (listOrder.Count == 0)
                {
                    MessageBox.Show("未找到相关记录");
                }
                else
                {
                    gridControlProduct.DataSource = listOrder;
                    gridControlProduct.RefreshDataSource();
                }
            }
            else if (e.ProgressPercentage == 100)
            {
                this.Cursor = Cursors.Default;
                buttonok.Enabled = true;
            }
            else
            {
                this.Cursor = Cursors.Default;
                buttonok.Enabled = true;
            }
        }

        private void backgroundWorkerselectProduct_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

        }

        private void backgroundWorkerSelectBill_DoWork(object sender, DoWorkEventArgs e)
        {
            backgroundWorkerSelectBill.ReportProgress(0, "");
            
            string ctmName = textBoxBCtmName.Text;
            string ProductName = textBoxBillId.Text;
            string startTime = dateTimePickerBillStart.Value.ToString("yyyy-MM-dd");
            string endTime = dateTimePickerBillEnd.Value.ToString("yyyy-MM-dd");


            string[] paraArray = new string[4] { ctmName, ProductName, startTime, endTime };
            try
            {
                List<SHOP_Bill_Info> listBill = query.BillQuery(paraArray, Shop.ShopId);
                backgroundWorkerSelectBill.ReportProgress(1, listBill);
            }
            catch
            {
                MessageBox.Show("连接冲印车间失败");

            }
            finally
            {
                backgroundWorkerSelectBill.ReportProgress(100, "");
            }

        }

        private void backgroundWorkerSelectBill_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 0)
            {
                this.Cursor = Cursors.WaitCursor;
                buttonBillOk.Enabled = false;
            }
            else if (e.ProgressPercentage == 1)
            {
                List<SHOP_Bill_Info> listBill = (List<SHOP_Bill_Info>)e.UserState;
                if (listBill.Count == 0)
                {
                    MessageBox.Show("未找到相关查询记录");
                }

                else
                {
                    gridControlBillMain.DataSource = listBill;
                    gridControlBillMain.RefreshDataSource();
                }
            }
            else if (e.ProgressPercentage == 100)
            {
                this.Cursor = Cursors.Default;
                buttonBillOk.Enabled = true;

            }
            else
            {
                this.Cursor = Cursors.Default;
                buttonBillOk.Enabled = true;

            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBoxrePricePWD.Text != textBoxPricePwd.Text)
            {
                MessageBox.Show("两次输入新密码不一致");
                return;
            }
            if (!string.IsNullOrEmpty(Properties.Settings.Default.PricePWD)&&!Md5HashCode.GetHash(textBoxOldPWD.Text).Equals(Properties.Settings.Default.PricePWD))
            {
                MessageBox.Show("输入旧密码不正确");
                return;
            }

            Properties.Settings.Default.PricePWD = Md5HashCode.GetHash(textBoxPricePwd.Text);
            Properties.Settings.Default.Save();
            MessageBox.Show("密码修改成功");
        }

        private void tabPage1_Click(object sender, EventArgs e)
        {

        }

        private void checkBoxDisplayPrice_CheckedChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Properties.Settings.Default.PricePWD))
            {
                FrmPwd frm = new FrmPwd();
                if (checkBoxDisplayPrice.Checked == true)
                {
                    if (frm.ShowDialog() == DialogResult.OK)
                    {
                        checkBoxDisplayPrice.Checked = true;
                    }
                    else
                    {
                        checkBoxDisplayPrice.Checked = false;
                    }

                }
                else
                {

                }
            }
            else
            {
 
            }
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            gridControlBillMain.DataSource = null;
            gridControlBillMain.RefreshDataSource();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FrmUnlock frm = new FrmUnlock();
            if (DialogResult.OK == frm.ShowDialog())
            {
                Properties.Settings.Default.PricePWD = "";

                Properties.Settings.Default.Save();
                MessageBox.Show("解锁成功，密码重置为空");
            }
            
        }



    }
}
